<?php
/**
 * 异步任务 By swoole
 * 只能用于linux 并安装swoole扩展
 * @author dem
 *
 */
class Server
{
    private $serv;
    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9599);
        $this->serv->set(array(
            'worker_num' => 4,   //一般设置为服务器CPU数的1-4倍
            'daemonize' => 1,  //以守护进程执行
            'dispatch_mode' => 2,
            'task_worker_num' => 50,  //task进程的数量
            'max_request' => 100,
            'package_max_length' => 8192,
            'open_eof_split' => true,
            'package_eof' => "\r\n"
        ));
        ini_set('default_socket_timeout', -1); //队列处理不超时,解决redis报错:read error on connection
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }
    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
        
        $data_list = explode("\r\n", $data);
        foreach ($data_list as $msg) {
            if($msg)
                $taskId = $serv->task($msg);
        }
    }
    /**
     * 执行任务
     * @param unknown $serv
     * @param unknown $task_id
     * @param unknown $from_id
     * @param unknown $data
     */
    public function onTask($serv,$task_id,$from_id, $data) {
        $array = json_decode( $data , true );
        if ($array['url']) {
            $params  = $array['data'];
            return $this->httpGet( $array['url']  );
        }
    }
    
    /**
     * 结束
     * @param unknown $serv
     * @param unknown $task_id
     * @param unknown $data
     */
    public function onFinish($serv,$task_id, $data) {


    }


    protected function httpGet($url,$data=array()){
        if ($data) {
            $url .='?'.http_build_query($data) ;
        }
        $curlObj = curl_init();    //初始化curl，
        curl_setopt($curlObj, CURLOPT_URL, $url);   //设置网址
        curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);  //将curl_exec的结果返回
        curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curlObj, CURLOPT_HEADER, 0);         //是否输出返回头信息
        $response = curl_exec($curlObj);   //执行
        curl_close($curlObj);          //关闭会话
        return $response;
    }
}
$server = new Server();
